package MapClass.Test;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class MyApp {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        System.out.println(args[0]);
        System.out.println(args[1]);
        Configuration conf =  new Configuration();
        Job job =Job.getInstance(conf,"word count");
        job.setJarByClass(MyApp.class);                             //运行本身这类
        job.setMapperClass(TokenizerMapper.class);                //指定Map的类
        job.setReducerClass(IntSumReducer.class);                //指定Reducer的类
        job.setOutputKeyClass(Text.class);                       //指定输入key类型
        job.setOutputValueClass(IntWritable.class);  //          //指定输出value类型
        FileInputFormat.addInputPath(job, new Path(args[0]));    //输入位置路径
        FileOutputFormat.setOutputPath(job, new Path(args[1]));  //输出位置路径
        System.exit(job.waitForCompletion(true) ? 0 : 1);

    }
    public static class TokenizerMapper
    extends Mapper<Object,Text, Text, IntWritable>{


        @Override
        protected void map(Object key,Text value,Context context
        ) throws IOException, InterruptedException {
            String[] strs = value.toString().split(", ");
            for (String word : strs) {
                context.write(new Text(word),new IntWritable(1));
            }


        }
    }

    public static class IntSumReducer extends Reducer<Text,IntWritable,Text,IntWritable> {
        @Override
        public void reduce(Text key, Iterable<IntWritable> values, Context context)
                throws IOException ,InterruptedException {
            int sum = 0;
            for (IntWritable val : values) {
                sum += val.get();
            }
            context.write(key, new IntWritable(sum));
        }
}}


